package com.fdsc.erp.weixin.Utils;

import com.fdsc.erp.weixin.Config;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;

/**
 * @Description:网络连接工具类
 * @Author:lishanhui
 * @Date:Create in 13:30  2018-06-06
 **/
public class CommonUtil {
    public static String POST = "POST";//POST请求
    public static String GET = "GET";//get请求
    /**
     * @param param
     * @Date:Create in 14:00 2018-06-06
     * @Description: Post请求
     * @params: * @param Url
     * @return:
     **/
    public static String doPost(String Url, String param) throws Exception {

        return send(Url, POST, param,null);
    }
    /**
     * @Date:Create in 14:00 2018-06-06
     * @Description: Post请求
     * @params: * @param Url
     * @return:
     **/
    public static String doPost(String Url,Map<String,String> parameters) throws Exception {

        return send(Url, POST, null,parameters);
    }
    /**
     * 不带参数的get请求
     * @param Url
     * @return
     * @throws Exception
     */
    public static String doGet(String Url) throws Exception {
        return send(Url, GET, null,null);
    }
    /**
     * 带参数的get请求
     * @param Url
     * @return
     * @throws Exception
     */
    public static String doGet(String Url,String param) throws Exception {
        return send(Url,GET,param,null);
    }
    /**
     * @param xmlData https Xml数据
     * @Date:Create in 13:48 2018-06-06
     * @Description:https请求
     * @params: * @param url https地址
     * @return: 请求响应
     **/
    private static String send(String Url, String method, String xmlData, Map<String,String> parameters) throws Exception {
        //建立连接
        URL url = new URL(Url);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        //使用自定义的信任管理器
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        connection.setSSLSocketFactory(ssf);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        //设置请求方式
        connection.setRequestMethod(method);

        //post请求拼接字符串
        if (method.equalsIgnoreCase("POST") & xmlData != null) {
            //向输出流写数据
            OutputStream out = connection.getOutputStream();
            out.write(xmlData.getBytes("utf-8"));
            out.close();
        }
        //psot请求 添加键值对数据
        if (method.equalsIgnoreCase(POST)&parameters!=null){
            StringBuffer param = new StringBuffer();
            for (String key : parameters.keySet()) {
                param.append("&");
                param.append(key).append("=").append(parameters.get(key));
            }
            connection.getOutputStream().write(param.toString().getBytes());
            connection.getOutputStream().flush();
            connection.getOutputStream().close();
        }
        //取得输入流
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        //读取响应内容
        StringBuffer buffer = new StringBuffer();
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        //关闭/释放资源
        bufferedReader.close();
        inputStream.close();
        inputStreamReader.close();
        connection.disconnect();
        return buffer.toString();
    }
    /**
     *@Date:Create in 16:34 2018-06-06
     *@Description:获取接口访问凭证
     *@params: * @param null
     *@return:
     **/
    public static Token getToken(){
        Token token = null;
        //发起GET请求获取凭证
        String resp = null;
        try {
            resp = doGet(Config.TOKENURL);
            //解析token
            JSONObject object = JSONObject.fromObject(resp);
            //接口访问凭证
            String accessToken = object.getString("access_token");
            //凭证有效期
            int expiresIn = object.getInt("expires_in");
            token = new Token();
            token.setAccessToken(accessToken);
            token.setExpiresIn(expiresIn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
}
